import { VUE_APP_API_URL } from "@/config";
import cookie from "@/utils/store/cookie"
import stringify from "@/utils/querystring";

const baseURL = VUE_APP_API_URL;

const token = 'token'

//获取token
function getToken() {
    return cookie.get(token);

}
// 请求完成时处理结果
function result(res, resolve, reject) {
    if (res && res != "") {
        let statusCode = res.statusCode;

        if (statusCode == 500) {
            shoToast('服务器出错：500');
            reject()
        } else {
            let result; //请求结果
            let status = ""; //请求结果中的status


            if (typeof (res.data) == 'string') {
                //返回的结果为string,转换为对象
                result = JSON.parse(resp.data);
            } else {
                result = res.data;
            }
            if (result.status) {
                status = result.status;
            }
            if (status == 200) {
                resolve(result)
            } else {
                showToast(result.msg)

                if (result.status == 401) {
                    setTimeout(() => {
                        uni.redirectTo({
                            url: '/pages/Login/index'
                        });
                    }, 500);
                }
                reject(result)
            }
        }

    }
}


//发送请求
function request(options) {
    return new Promise((resolve, reject) => {

        //判断dataType不存在或为空则设置为json格式
        if (!options.dataType) {
            options.dataType = 'json'
        }

        //判断参数不存在或为空则设置为空对象
        if (options.params) {
            options.url += '?' + stringify(options.params)
        }


        //请求头
        const header = {
            'Content-Type': "application/json",
            ...options.header,
        }

        if (getToken()) {
            header[token] = getToken();
        }


        uni.request({
            url: baseURL + options.url, //仅为示例，并非真实接口地址。
            data: options.data,
            method: options.method,
            header: header,
            dataType: options.dataType,
            success: (res) => {
                result(res, resolve, reject)
            },
            fail: (err) => {
                let errMsg = "";
                if (err != undefined && err.errMsg != undefined) {
                    errMsg = error.errMsg;
                }
                showToast("连接失败：服务器出错:" + errMsg);
                reject();
            }
        });
    })

}
//提示信息
export function showToast(title, position = "center", icon = "none", duration = 2000) {
    uni.showToast({
        title,
        position,
        icon,
        duration
    });
}

export default request
